#!/bin/bash
# Copyright 2019  Lantian Li
# Apache 2.0.

# This computes the diag-GMM likelihood or full-GMM likelihood.

# Begin configuration section.
nj=8
cmd=run.pl
diag=true
apply_cmn=true # If true, apply sliding window cepstral mean normalization
# End configuration section.

echo "$0 $@"  # Print the command line for logging

if [ -f path.sh ]; then . ./path.sh; fi
. parse_options.sh || exit 1;

if [ $# != 3 ]; then
  echo "Usage: sid/gmm_likelihood.sh <data> <ubm-dir> <likelihood-dir>"
  echo "Computes the diag-GMM likelihood or full-GMM likelihood."
  echo " e.g.: sid/gmm_likelihood.sh data/train exp/diag_ubm score/diag_ubm/train"
  echo "main options (for others, see top of script file)"
  echo "  --cmd (utils/run.pl|utils/queue.pl <queue opts>) # how to run jobs."
  echo "  --nj <n|16>                                      # number of parallel training jobs"
  echo "  --diag <true,false|true>                         # diag or full-GMM"
  echo "  --apply-cmn <true,false|true>                    # if true, apply sliding window cepstral mean"
  echo "                                                   # normalization to features"
  exit 1;
fi

data=$1
srcdir=$2
dir=$3

for f in $data/feats.scp; do
  [ ! -f $f ] && echo "No such file $f" && exit 1;
done

# Set various variables.
mkdir -p $dir/log
echo $nj > $dir/num_jobs
sdata=$data/split$nj;
utils/split_data.sh $data $nj || exit 1;

delta_opts=`cat $srcdir/delta_opts 2>/dev/null`

## Set up features.
if $apply_cmn; then
    feats="ark,s,cs:copy-feats scp:$sdata/JOB/feats.scp ark:- | apply-cmvn-sliding --norm-vars=false --center=true --cmn-window=300 ark:- ark:- |"
else
    feats="ark,s,cs:copy-feats scp:$sdata/JOB/feats.scp ark:- |"
fi

if $diag; then
  if [ ! -f $srcdir/final.dubm ]; then
    echo "$0: in $srcdir, expecting final.dubm to exist"
    exit 1;
  fi
  echo compute log-likelihood on diag-GMM.
  $cmd JOB=1:$nj $dir/log/diag_gmm.JOB.log \
   gmm-global-get-frame-likes --average=true \
    $srcdir/final.dubm "$feats" ark,t:$dir/diag_gmm.JOB.foo

  echo "$0: combining foos across jobs"
  for j in $(seq $nj); do cat $dir/diag_gmm.$j.foo; done >$dir/diag_gmm.foo || exit 1;
  rm $dir/diag_gmm.*.foo
else
  if [ ! -f $srcdir/final.ubm ]; then
    echo "$0: in $srcdir, expecting final.ubm to exist"
    exit 1;
  fi
  echo compute log-likelihood on full-GMM.
  $cmd JOB=1:$nj $dir/log/full_gmm.JOB.log \
   fgmm-global-get-frame-likes --average=true \
    $srcdir/final.ubm "$feats" ark,t:$dir/full_gmm.JOB.foo

  echo "$0: combining foos across jobs"
  for j in $(seq $nj); do cat $dir/full_gmm.$j.foo; done >$dir/full_gmm.foo || exit 1;
  rm $dir/full_gmm.*.foo
fi
